import { getTokenAsync, isTauri } from './secure-storage';
import { API_BASE_URL } from '@/config/env';

export interface ImChat {
  chat_id: string;
  chat_type: number;
  owner_id?: string;
  to_id: string;
  is_mute: number;
  is_top: number;
  sequence?: number;
  read_sequence?: number;
  create_time?: number;
  update_time?: number;
  del_flag?: number;
  version?: number;
  name?: string; // 群组名称或用户名
  member_count?: number; // 群组人数（仅群组有效）
}

export interface CreateChatRequest {
  chat_id: string;
  chat_type: number;
  to_id: string;
}

export interface UpdateChatRequest {
  is_top?: number;
  is_mute?: number;
}

export const getUserChats = async (): Promise<ImChat[]> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/chats`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取聊天列表失败' }));
    throw new Error(error.message || '获取聊天列表失败');
  }

  const data = await response.json();
  return data.chats || [];
};

export const getOrCreateChat = async (req: CreateChatRequest): Promise<ImChat> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/chats`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(req),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '创建或获取聊天失败' }));
    throw new Error(error.message || '创建或获取聊天失败');
  }

  return response.json();
};

export const updateChat = async (chat_id: string, req: UpdateChatRequest): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/chats/${encodeURIComponent(chat_id)}`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(req),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '更新聊天失败' }));
    throw new Error(error.message || '更新聊天失败');
  }
};

export const deleteChat = async (chat_id: string): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/chats/${encodeURIComponent(chat_id)}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '删除聊天失败' }));
    throw new Error(error.message || '删除聊天失败');
  }
};

export interface UnreadStats {
  total_unread: number;
  single_chat_unread: number;
  group_chat_unread: number;
  unread_chats: Array<{
    chat_id: string;
    chat_type: number;
    to_id: string;
    name: string;
    unread_count: number;
  }>;
}

export const getUnreadStats = async (): Promise<UnreadStats> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/chats/unread-stats`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取未读消息统计失败' }));
    throw new Error(error.message || '获取未读消息统计失败');
  }

  return response.json();
};

export const updateReadSequence = async (chat_id: string, read_sequence: number): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/chats/${encodeURIComponent(chat_id)}/read-sequence`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ read_sequence }),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '更新已读序列号失败' }));
    throw new Error(error.message || '更新已读序列号失败');
  }
};

// 更新群聊备注（仅自己可见）
export const updateChatRemark = async (chat_id: string, remark: string | null): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/chats/${encodeURIComponent(chat_id)}/remark`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ remark: remark || null }),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '更新群聊备注失败' }));
    throw new Error(error.message || '更新群聊备注失败');
  }
};

